# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, execjs
from common.helper import Helper
from threading import Thread
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "瑞华爱宝保少儿重大疾病保险"
        self.filename = "commonJS"
    #生产产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                #年龄段
                "year":[str(i) for i in range(0,18)],
                # 性别
                "gender":["M","F"],
                #有无社保
                "socialSec":["Y"],
                #保额
                "money":["300000","500000","800000","1000000"],
                #保障期限
                "expire":["20年","25年","30年","终身"],
                #缴费间隔
                "interval":["0","5","10","15","20"],
                #缴费方式
                "payType":["年缴","半年缴","季缴","月缴"],
                # 投保人保费豁免 0 不包含
                "ext_money": ["0"],
                # 投保人年收入
                "year_income": [">50000"]

            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 有无社保
                "socialSec": ["N"],
                # 保额
                "money": ["300000", "500000","800000"],
                # 保障期限
                "expire": ["20年", "25年", "30年", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 缴费方式
                "payType": ["年缴", "半年缴", "季缴", "月缴"],
                #投保人保费豁免 0 不包含
                "ext_money":["0"],
                #投保人年收入
                "year_income":[">50000"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 有无社保
                "socialSec": ["Y"],
                # 保额
                "money": ["300000", "500000"],
                # 保障期限
                "expire": ["20年", "25年", "30年", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 缴费方式
                "payType": ["年缴", "半年缴", "季缴", "月缴"],
                # 投保人保费豁免 0 不包含
                "ext_money": ["0"],
                # 投保人年收入
                "year_income": ["<50000"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 有无社保
                "socialSec": ["N"],
                # 保额
                "money": ["300000", "500000"],
                # 保障期限
                "expire": ["20年", "25年", "30年", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 缴费方式
                "payType": ["年缴", "半年缴", "季缴", "月缴"],
                # 投保人保费豁免 0 不包含
                "ext_money": ["0"],
                # 投保人年收入
                "year_income": ["<50000"]
            }

        }

        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["socialSec"],plan[k]["money"],plan[k]["expire"],plan[k]["interval"],plan[k]["payType"],plan[k]["ext_money"],plan[k]["year_income"]):
                if v[5] == "0":
                    payType = "一次缴清"
                    self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                        v[0],v[1],v[2],v[3],v[4],v[5],payType,v[7],v[8]
                    ))
                    self.mysql._conn.commit()
                    print( domain[self.name]["insert_sql"].format(
                        v[0],v[1],v[2],v[3],v[4],v[5],payType,v[7],v[8]
                    ))

                else:
                    self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                        v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]
                    ))

                    self.mysql._conn.commit()
                    print(domain[self.name]["insert_sql"].format(
                        v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]
                    ))
        # 获取请求参数

    def RequestJson(self, dt=None, mysql=None):

        sex = "m" if dt["gender"] == "M" else "f"
        if dt["expire"] == "终身":
            expire = "106"
            yearFlag = "A"
        else:
            expire =dt["expire"].replace("年", "")
            yearFlag = "Y"

        year = str(int(2020 - int(dt["year"])))
        interval = "1" if dt["interval"] == "0" else dt["interval"]
        if dt["payType"] == "年缴":
            payType = "12"
        elif dt["payType"] == "半年缴":
            payType = "6"
        elif dt["payType"] == "季缴":
            payType = "3"
        elif dt["payType"] == "月缴":
            payType = "1"
        else:
            payType = "0"
        if dt["year_income"] == ">50000":
            income = "1"
        else:
            income = "0"
        if dt["socialSec"] == "Y":
            socialSec = "1"
        else:
            socialSec = "0"
        data = {
            "transfer": "GTO2OINTERFACE2017#@!%88",
            "payload":'{"base":{"NAmt":"'+dt["money"]+'","CInsuYear":"'+expire+'","CFinTyp":"'+payType+'","NPayTime":"'+interval+'","CArea":"310000","CProdNo":"990005","CInsuYearFlag":"'+yearFlag+'"},"applicant":{"TBirthday":"","CSex":"m","NRevenueSel":"'+income+'"},"insured":{"TBirthday":"'+year+'-01-01","CSex":"'+sex+'","CIsSoc":"'+socialSec+'","CCusLvl":"1"},"cvrgList":[{"CCvrgNo":"301022","CCustCvrgNme":"瑞华少儿特定重疾保险","NAmt":"'+dt["money"]+'","CProdNo":"300022","CNmeCn":"瑞华少儿特定重疾保险","NDductAmt":""}],"prodList":[{"CProdNo":"300022","CProdName":"瑞华爱宝保少儿重大疾病保险","CFinTyp":"'+payType+'","NPayTime":"'+interval+'","CInsuYear":"'+expire+'","CInsuYearFlag":"'+yearFlag+'","NHsttPrd":15,"NDssWtPrd":180,"CRdrProd":"0","NGrntExtInsr":-2,"CAutoPadding":"1"}]}'
        }
        packJS = open('./' + self.filename + '/packageList.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(packJS)

        # 获取packageList参数值
        packageList = cxt.call("genPackageList", data["payload"])

        form_data = '{"packageList":{"packages":{"header":{"requestType":"RHCALCULATION","comId":"GTO2O20170118","from":"iwechat","sendTime":"' + \
                    packageList["packageList"]["packages"]["header"][
                        "sendTime"] + '","orderSerial":"orderId","comSerial":"comSerial"},"request":"' + \
                    packageList["packageList"]["packages"]["request"] + '"}}}'

        signJS = open('./' + self.filename + '/sign.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(signJS)

        # 获取加密签名
        sign = cxt.call("hex_hmac_md5", data["transfer"], packageList)
        session = requests.session()
        r = session.post(url=domain[self.name]["url"] + "sign=" + sign + "&com_id=GTO2O20170118",
                          headers=domain[self.name]["header"], data=form_data)

        if r.status_code == 200 and "response" in r.text:
            data = (r.json()["packageList"]["packages"]["response"])

            res = self.responseDecode(data)

            result = json.loads(res['responsePayload']["data"])

            price = Helper.decimalParse(result["calPremium"]["cvrgList"][0]["NPrm"])

            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格更新失败:%d*/" % dt["id"])
    # 解码
    def responseDecode(self, data):
        JSdecode = open('./' + self.filename + '/decode.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(JSdecode)

        response = cxt.call("decrypt", "", data)

        return response
        # 主函数

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.RequestJson(dt, mysql)

    # 多线程
    def startProcess(self):
        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

